<template>
  <div>
    <div class="flex align-center p-30">
      <div class="avatar">
        <van-image
          round
          width="10rem"
          height="10rem"
          :src="avatar"
        />
        <van-uploader class="upload" :preview-image="false" :after-read="afterRead" />
      </div>
      <div class="m-l-15">
        <h2>{{userInfo.username}}</h2>
        <p class="m-t-15">千锋大学</p>
      </div>
    </div>
    <van-cell title="我的兼职" is-link />
    <van-cell title="我的实习" is-link />
    <div class="p-30">
      <van-button @click="logout" type="danger" block>退出登录</van-button>
    </div>
  </div>
</template>

<script>
  import request from '../utils/request'
  import {userUpdate} from '../api/user'
  import {BASE} from '../config/index'
  export default {
    data() {
      return {
        // avatar:'https://img01.yzcdn.cn/vant/cat.jpeg'
      }
    },
    computed: {
      userInfo() {
        return this.$store.state.user.userInfo 
      },
      avatar(){ //根据用户的登录情况，动态获取头像
        let avatar = 'https://img01.yzcdn.cn/vant/cat.jpeg' //默认头像
        let {userInfo} = this
        if(userInfo&&userInfo.avatar){
          avatar = `${BASE}${userInfo.avatar}` //用户上传过的头像
        }
        return avatar
      }
    },
    methods: {
      logout() {
        this.$store.commit('user/initUserInfoMut',null)
        localStorage.removeItem('userInfo')
        this.$router.push('/')
      },
      afterRead(file) {
        // 此时可以自行将文件上传至服务器
        console.log(file);
        let formData = new FormData()  //Form对象
        formData.append('picture',file.file) //将图片资源对象存入form对象
        request.post('/upload',formData).then(res=>{ //上传图片
          // this.avatar = `http://localhost:3001${res.data.data}`
          let info = {
            ...this.userInfo,
            avatar:res.data.data
          }
          userUpdate(this.userInfo._id,{ //更新数据库
            avatar:res.data.data
          }).then(res=>{
            this.$store.commit('user/initUserInfoMut',info) //更新状态机
            localStorage.removeItem('userInfo',JSON.stringify(info)) //更新本地存储
          })
        })
      },
    },
  }
</script>

<style lang="less" scoped>
.avatar{
  // border: 1px solid red;
  position: relative;
  overflow: hidden;
  .upload{
    position: absolute;
    top: 0;
    left: 0;
    opacity: 0;
  }
}
</style>